package com.my.util;

import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.ThreadNameDeterminer;

import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * @author Hujf
 * @title: Threads
 * @date 2021-09-09 17:09
 * @description: dealing with threads, timers and the like.
 */
public class Threads {

    /** Used to count HashedWheelTimers */
    final static AtomicInteger TIMER_ID = new AtomicInteger();

    public static HashedWheelTimer newTimer(String name) {
        return newTimer(100, name);
    }

    public static HashedWheelTimer newTimer(final int ticks, final String name) {
        return newTimer(ticks, 512, name);
    }

    public static HashedWheelTimer newTimer(final int ticks,
                                            final int ticks_per_wheel, final String name) {
        class TimerThreadNamer implements ThreadNameDeterminer {
            @Override
            public String determineThreadName(String currentThreadName,
                                              String proposedThreadName) throws Exception {
                return "OpenTSDB Timer " + name + " #" + TIMER_ID.incrementAndGet();
            }
        }
        return new HashedWheelTimer(Executors.defaultThreadFactory(),
                new TimerThreadNamer(), ticks, MILLISECONDS, ticks_per_wheel);
    }

    public static class WorkerThreadNamer implements ThreadNameDeterminer{
        final static AtomicInteger tid = new AtomicInteger();
        @Override
        public String determineThreadName(String currentThreadName, String proposedThreadName) throws Exception {
            return "Yarn I/O Worker #" + tid.incrementAndGet();
        }
    }

    public static class PrependThreadNamer implements ThreadNameDeterminer{
        final static AtomicInteger tid = new AtomicInteger();
        @Override
        public String determineThreadName(String currentThreadName, String proposedThreadName) throws Exception {
            return "Yarn " + tid.incrementAndGet();
        }
    }
}
